package com.mapbased.sfw.site;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.mapbased.sfw.model.Site;
import com.mapbased.sfw.store.FSSiteStore;
import com.mapbased.sfw.store.SiteStore;

public class SiteManager {
	ConcurrentMap<String, SiteBag> sites = new ConcurrentHashMap<String, SiteBag>();

	public Site getSite(String domain) {
		domain = domain.toLowerCase();
		SiteBag bag = sites.get(domain);
		if (bag == null) {
			bag = new SiteBag();
			SiteBag old = sites.putIfAbsent(domain, bag);
			if (old != null) {
				bag = old;
			}

		}
		bag.lastAccessTime.set((int) (System.currentTimeMillis() / 1000L));
		Site s = bag.site;
		if (s == null) {
			this.checkSite(bag, domain);
		}
		return bag.site;
	}

	private void checkSite(SiteBag bag, String domain) {

		if (System.currentTimeMillis() - bag.lastCheckTime < 2000L) {
			return;
		}

		SiteStore ss = this.createSiteStore(domain);
		bag.lastCheckTime = System.currentTimeMillis();
		if (!ss.exist()) {
			return;
		}
		synchronized (bag) {
			if (bag.site == null) {
				bag.site = new Site(ss);
			}

		}

	}

	private SiteStore createSiteStore(String domain) {
		return new FSSiteStore(domain);
	}
}
